<template>
  <Container class="user-security">
    <div class="box">
      <div class="box-header">
        <Icon type="ios-star"></Icon>
        安全等级
      </div>
      <div class="box-body">
        <div class="password-strong">
          <span>安全强度：</span>
          <span class="password-strong-item bg-red">弱</span>
          <span class="password-strong-item bg-orange">中</span>
          <span class="password-strong-item bg-green">强</span>
        </div>
      </div>
    </div>
    <Row class="mt">
      <Col span="12">
        <div class="box">
          <div class="box-header">
            <Icon type="md-lock"></Icon>
            登录密码
            <span class="password-strong big ml font-gray">
              (
              <span>密码强度:</span>
              <span class="password-strong-item bg-red" v-if="level === 1 || level === 0">弱</span>
              <span class="password-strong-item bg-orange" v-if="level === 2">中</span>
              <span class="password-strong-item bg-green" v-if="level === 3">强</span>
              )
            </span>
          </div>
          <div class="box-body">
            <p class="info">安全性高的密码可以使账号更安全。建议您定期更换密码，且设置一个包含数字和字母，并长度超过6位以上的密码。</p>
            <Button type="primary" @click="passwordForm.model = true">修改密码</Button>
          </div>
        </div>
      </Col>
      <Col span="12">
        <div class="box ml">
          <div class="box-header">
            <Icon type="md-phone-portrait"></Icon>
            手机号码
            <span class="ml big" v-if="tel">
              ({{tel}})
            </span>
          </div>
          <div class="box-body">
            <p class="info">该手机号用于接收登录提醒，登录验证码，余额提醒消息。</p>
            <Button type="primary" @click="changeTel">修改手机号</Button>
          </div>
        </div>
      </Col>
    </Row>
    <Row class="mt">
      <Col span="12">
        <div class="box">
          <div class="box-header">
            <Icon type="ios-notifications"></Icon>
            登录提醒
            <span class="big ml">({{tip ? '已开启' : '已关闭'}})</span>
          </div>
          <div class="box-body">
            <p class="info">登录时会收到短信提醒，及时了解非法登录，预防账号被盗。</p>
            <Button type="primary" @click="toggleTip">{{tip ? '关闭提醒' : '开启提醒'}}</Button>
          </div>
        </div>
      </Col>
    </Row>
    <Modal 
        v-model="passwordForm.model" 
        :mask-closable="false" 
        title="修改密码">
        <Form ref="form" :label-width="80" :model="passwordForm" :rules="rules">
          <FormItem label="旧密码" prop="oldpassword">
            <Input v-model="passwordForm.oldpassword" placeholder="请输入旧密码" type="password" :maxlength="18"/>
          </FormItem>
          <FormItem label="新密码" prop="password">
            <Input v-model="passwordForm.password" @input="setPosswordLevel" placeholder="请输入新密码" type="password" :maxlength="18"/>
            <div class="password-strong mt">
              <span>密码强度：</span>
              <span class="password-strong-item" :class="{'bg-red': passwordForm.level === 1}">弱</span>
              <span class="password-strong-item" :class="{'bg-orange': passwordForm.level === 2}">中</span>
              <span class="password-strong-item" :class="{'bg-green': passwordForm.level === 3}">强</span>
            </div>
          </FormItem>
          <FormItem label="确认密码" prop="repassword">
            <Input v-model="passwordForm.repassword" placeholder="请再输入一遍密码" type="password" :maxlength="18"/>
          </FormItem>
        </Form>
        <Button type="text" size="large" slot="footer" @click="passwordForm.model = false">取消</Button>
        <Button type="primary" size="large" slot="footer" @click="onDoneBtnClick">确定</Button>
        <Loader :status="passwordForm.status"></Loader>
    </Modal>
    <Modal class="security-model" v-model="telForm.model" title="重新绑定手机" :closable="false" :mask-closable="false">
      <Form @submit.native.prevent :label-width="120" v-if="telForm.step === 1">
        <FormItem label="手机号码">
          {{tel}}
        </FormItem>
        <FormItem label="短信验证码">
          <Row>
            <Col span="17">
              <div class="security-cell">
                <Input :maxlength="6" ref="dxCode" placeholder="请输入短信验证码" @keydown.native.enter="telStep3" v-model="telForm.dxCode"/>
                <span class="cursor extend link" v-if="telForm.rePostTime <= 0" @click="telStep2">发送短信验证码</span>
                <span class="extend" v-else>{{telForm.rePostTime}} 秒后重新发送</span>
              </div>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <Form @submit.native.prevent :label-width="120" v-if="telForm.step === 2">
        <FormItem label="新手机号码">
          <Row>
            <Col span="17">
              <div class="security-cell">
                <Input :maxlength="11" placeholder="请输入新手机号" v-model="telForm.newTel"/>
              </div>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="短信验证码">
          <Row>
            <Col span="17">
              <div class="security-cell">
                <Input :maxlength="6" ref="newDxCode" placeholder="短信验证码" @keydown.native.enter="telStep6" v-model="telForm.newDxCode"/>
                <span class="cursor link extend" @click="telStep5" v-if="telForm.rePostNewTime <= 0">发送短信验证码</span>
                <span class="extend" v-else>{{telForm.rePostNewTime}} 秒后重新发送</span>
              </div>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <Button type="text" size="large" slot="footer" @click="telForm.model = false">取消</Button>
      <Button type="primary" size="large" slot="footer" @click="telStep3" v-if="telForm.step === 1">下一步</Button>
      <Button type="primary" size="large" slot="footer" @click="telStep6" v-if="telForm.step === 2">完成</Button>
      <Loader :status="telForm.status"></Loader>
    </Modal>
  </Container>
</template>

<script>
import { telReg } from '@/util'
export default {
  data() {
    const repasswordCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      cellCode: '', //新手机验证码
      code: '', //原手机验证码
      newPhone: '', //新手机
      passwordForm: {
        model: false,
        oldpassword: '',
        password: '',
        repassword: '',
        level: 0,
        status: 'pass'
      },
      telForm: {
        step: 1,
        model: false,
        dxCode: '',
        rePostTime: 0,
        newTel: '',
        newDxCode: '',
        rePostNewTime: 0,
        status: 'pass'
      },
      telFormBack: {},
      tel: '',
      level: null,
      tip: false,
      rules: {
        oldpassword: [{ required: true, message: '请填写密码', trigger: 'blur' }],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        repassword: [
          { required: true, validator: repasswordCheck, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getUserData()
    this.telFormBack = {
      ...this.telForm
    }
  },
  methods: {
    getUserData() {
      this.$ajaxGet('/supplier/supplier_user/find_admin').then(data => {
        this.id = data.id
        this.tel = data.mobile
        this.tip = data.isLoginRemind
        this.level = data.passwordStrength
      })
    },
    onDoneBtnClick() {
      if (this.passwordForm.status === 'loading') return
      if (this.passwordForm.oldpassword == this.passwordForm.password) {
        this.$Notice.error({
          title: '修改失败',
          desc: '新密码和旧密码一样'
        })
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let postData = {
            id: this.id,
            newPassword: this.passwordForm.password,
            password: this.passwordForm.oldpassword,
            passwordStrength: this.passwordForm.level
          }
          this.passwordForm.status = 'loading'
          this.$jsonPost('/supplier/supplier_user/update_pwd', postData).then(() => {
            this.$Notice.success({
              title: '修改成功',
              desc: '修改密码成功！'
            })
            this.level = this.passwordForm.level
            this.$refs.form.resetFields()
            this.passwordForm = {
              model: false,
              oldpassword: '',
              password: '',
              repassword: '',
              level: 0
            }
            this.passwordForm.status = 'pass'
          }).catch(() => {
            this.passwordForm.status = 'pass'
          })
        }
      })
    },
    // 检测强度
    setPosswordLevel(val) {
      let lv = 0
      if (val.match(/[a-z]/g)) {
        lv++
      }
      if (val.match(/[0-9]/g)) {
        lv++
      }
      if (val.match(/(.[^a-z0-9])/g)) {
        lv++
      }
      if (val.length < 6) {
        lv = 0
      }
      if (lv > 3) {
        lv = 3
      }
      this.passwordForm.level = lv
    },
    changeTel() {
      this.telForm = {
        ...this.telFormBack
      }
      this.telForm.model = true
    },
    // 2.更换手机发送旧手机验证码
    telStep2() {
      this.$jsonPost('/supplier/supplier_user/send_bind_message').then(data => {
        this.$Notice.success({
          title: '发送验证码',
          desc: '发送成功'
        })
        this.$refs.dxCode.focus()
        this.telForm.rePostTime = 60
        this.countDown()
      })
    },
    countDown() {
      if (this.telForm.rePostTime >= 1) {
        this.telForm.rePostTime -= 1
        setTimeout(() => {
          this.countDown()
        }, 1000)
      }
    },
    // 3.检测旧手机验证码
    telStep3() {
      this.telForm.step = 2
      // if (!this.telForm.dxCode.length) {
      //   this.$Notice.info({
      //     title: '校验错误',
      //     desc: '请输入短信验证码'
      //   })
      //   return
      // }
      // let param = {
      //   code: this.telForm.dxCode
      // }
      // this.$ajaxPost('/supplier/supplier_user/mobile_valid_bind', param).then(data => {
      //   this.telForm.step = 2
      // })
    },
    // 5.发送新手机验证码
    telStep5() {
      let param = {
        newPhone: this.telForm.newTel
      }
      this.$jsonPost('/supplier/supplier_user/send_bind_new_message', param).then(data => {
        this.$Notice.success({
          title: '发送验证码',
          desc: '发送成功'
        })
        this.$refs.newDxCode.focus()
      })
    },
    // 6.绑定新手机
    telStep6() {
      if (this.telForm.status === 'loading') return
      if (!this.telForm.newDxCode) {
        this.$Notice.info({
          title: '校验错误',
          desc: '请输入短信验证码'
        })
        return
      }
      let param = {
        newPhone: this.telForm.newTel,
        cellCode: this.telForm.newDxCode,
        code: this.telForm.dxCode
      }
      this.telForm.status === 'loading'
      this.$jsonPost('/supplier/supplier_user/mobile_valid_bind', param).then(data => {
        this.$Notice.success({
          title: '修改成功',
          desc: '修改新手机成功！'
        })
        this.tel = this.telForm.newTel
        this.telForm.model = false
        this.telForm.status === 'pass'
      }).catch(() => {
        this.telForm.status = 'pass'
      })
    },
    toggleTip() {
      this.tip = !this.tip
      this.$jsonPost('/supplier/supplier_user/change_remind?remind='+ this.tip).then(data => {
        this.$Notice.success({
          title: '修改成功',
          desc: `已经${this.tip ? "开启" : "关闭"}提醒`
        })
        this.getUserData()
      })
    }
  }
}
</script>